<template>
  <!-- 购买或者加入购物车的时候选择商品的种类 -->
  <u-popup
    mode="bottom"
    v-model="showTimePopup"
    :z-index="121"
    border-radius="24"
    safe-area-inset-bottom
  >
    <view class="popup-body">
      <view class="popup-title"> 请选择入住离店日期 </view>
      <view class="time-list">
        <view class="week-list">
          <view
            :class="['week-item', index == 0 || index == 6 ? 'weekend' : '']"
            v-for="(item, index) in weekData"
            :key="index"
          >
            {{ item }}</view
          >
        </view>
        <scroll-view
          class="scroll-section"
          scroll-y="true"
          v-if="timeData.length"
        >
          <view
            class="time-item"
            v-for="(item, index) in timeData"
            :key="index"
          >
            <view class="time-title">{{ item.monthTitle }}</view>
            <view class="time-calendar">
              <view
                :class="[
                  'calendar-item',
                  !time.show ? 'calendar-hide' : '',
                  startI == i && startFatherIndex == index ? 'range-item' : '',
                  endI == i && endFatherIndex == index ? 'range-item' : '',
                  item.rangeStart < i && i < item.rangeEnd ? 'in-range' : '',
                  startI == i &&
                  startFatherIndex == index &&
                  startFatherIndex < endFatherIndex
                    ? 'start-range-item'
                    : '',
                  startI == i &&
                  startFatherIndex == index &&
                  startFatherIndex > endFatherIndex
                    ? 'end-range-item'
                    : '',
                  endI == i &&
                  endFatherIndex == index &&
                  startFatherIndex > endFatherIndex
                    ? 'start-range-item'
                    : '',
                  endI == i &&
                  endFatherIndex == index &&
                  startFatherIndex < endFatherIndex
                    ? 'end-range-item'
                    : '',
                  startI == i &&
                  startFatherIndex == index &&
                  startFatherIndex == endFatherIndex &&
                  startI > endI
                    ? 'end-range-item'
                    : '',
                  startI == i &&
                  startFatherIndex == index &&
                  startFatherIndex == endFatherIndex &&
                  startI < endI
                    ? 'start-range-item'
                    : '',
                  endI == i &&
                  endFatherIndex == index &&
                  startFatherIndex == endFatherIndex &&
                  startI < endI
                    ? 'end-range-item'
                    : '',
                  endI == i &&
                  endFatherIndex == index &&
                  startFatherIndex == endFatherIndex &&
                  startI > endI
                    ? 'start-range-item'
                    : '',
                  startI == i &&
                  startFatherIndex == index &&
                  startFatherIndex &&
                  startI &&
                  !endI &&
                  !endFatherIndex
                    ? 'has-radius'
                    : '',
                  time.num === 0 ? 'disabled' : '',
                ]"
                v-for="(time, i) in item.list"
                :key="i"
                @click="handleTimeItem(time, i, index)"
              >
                <view class="day-text">{{ time.day_text || "" }}</view>
                <view class="day-time">{{ time.day }}</view>
                <!-- <view class="day-down">{{
                  time.canSelect ? "¥" + time.price : ""
                }}</view> -->
                <view class="day-down">库存:{{ time.num }}</view>
              </view>
            </view>
          </view>
        </scroll-view>
      </view>
      <view class="close-icon" @click="hidePopup">
        <view class="icon-box">
          <i class="iconfont icon-close"></i>
        </view>
      </view>

      <!-- 底部按钮 -->
      <view class="foot-btns">
        <!-- <view class="selected-section">
          <view class="select-title">
            <view class="start">入住</view>
            <view class="middle"></view>
            <view class="end">离店</view>
          </view>
          <view class="select-date">
            <view class="selected-start">{{ selectStart }}</view>
            <view class="split-line">-</view>
            <view class="selected-end">{{ selectEnd }}</view>
          </view>
        </view> -->
        <view class="select-num">
          <view class="shop-num-text"> 数量 </view>
          <view>
            <u-number-box v-model="num"></u-number-box>
          </view>
        </view>
        <view class="foot-content">
          <view
            :class="['foot-btn', totalDays == 0 ? 'btn-grey' : '']"
            @click="confirmTime"
            >确定{{ totalDays }}晚</view
          >
        </view>
      </view>
    </view>
  </u-popup>
</template>

<script>
export default {
  name: "",

  props: {
    serveData: {
      type: Object,
      default: {},
    },
    hotelData: {
      type: Object,
      default: {},
    },
    product_type: {
      type: null,
      default: "",
    },
  },

  data() {
    return {
      checkList: [],
      showTimePopup: false,
      weekData: ["日", "一", "二", "三", "四", "五", "六"],
      timeData: [],
      startTime: null,
      endTime: null,
      startFatherIndex: null,
      startI: null,
      endFatherIndex: null,
      endI: null,
      num: 1,
    };
  },

  computed: {
    totalDays() {
      if (this.startTime && this.endTime) {
        // 同一个月内
        if (this.startFatherIndex == this.endFatherIndex) {
          return Math.abs(this.startTime.day - this.endTime.day);
        }
        let monthBigger = ["01", "03", "05", "07", "08", "10", "12"];
        // 正常选择跨月
        if (this.startFatherIndex < this.endFatherIndex) {
          let monthDay = 30;
          if (this.startTime.month == 2) {
            monthDay = 28;
          }
          if (monthBigger.includes(this.startTime.month)) {
            monthDay = 31;
          }
          let start = monthDay - this.startTime.day;
          let end = 0;
          let arr = this.timeData[this.endFatherIndex].list;
          arr.forEach((d, index) => {
            if (d.canSelect && index <= this.endI) {
              end++;
            }
          });
          return end + start;
        }
        // 反选跨月
        if (this.startFatherIndex > this.endFatherIndex) {
          let monthDay = 30;
          if (this.endTime.month == 2) {
            monthDay = 28;
          }
          if (monthBigger.includes(this.endTime.month)) {
            monthDay = 31;
          }
          let start = monthDay - this.endTime.day;
          let end = 0;
          let arr = this.timeData[this.startFatherIndex].list;
          arr.forEach((d, index) => {
            if (d.canSelect && index <= this.startI) {
              end++;
            }
          });
          return end + start;
        }
      }
      return 0;
    },

    selectStart() {
      let isStart = true;
      if (this.startTime || this.endTime) {
        if (this.startTime && !this.endTime) {
          isStart = true;
        }
        if (!this.startTime && this.endTime) {
          isStart = false;
        }
        if (this.startTime && this.endTime) {
          if (this.startTime.year < this.endTime.year) {
            isStart = true;
          }
          if (this.startTime.year > this.endTime.year) {
            isStart = false;
          }
          if (this.startTime.year == this.endTime.year) {
            if (this.startTime.month < this.endTime.month) {
              isStart = true;
            }
            if (this.startTime.month > this.endTime.month) {
              isStart = false;
            }
            if (this.startTime.month == this.endTime.month) {
              if (this.startTime.day < this.endTime.day) {
                isStart = true;
              }
              if (this.startTime.day > this.endTime.day) {
                isStart = false;
              }
            }
          }
        }
        if (isStart) {
          return `${this.startTime.month}月${this.startTime.day}日${
            this.startTime.day_text
              ? this.startTime.day_text
              : "周" + this.weekData[this.startTime.week]
          }`;
        } else {
          return `${this.endTime.month}月${this.endTime.day}日${
            this.endTime.day_text
              ? this.endTime.day_text
              : "周" + this.weekData[this.endTime.week]
          }`;
        }
      }
      return "";
    },
    selectEnd() {
      let isEnd = true;
      if (!this.startTime || !this.endTime) {
        return "";
      }
      if (this.startTime.year < this.endTime.year) {
        isEnd = true;
      }
      if (this.startTime.year > this.endTime.year) {
        isEnd = false;
      }
      if (this.startTime.year == this.endTime.year) {
        if (this.startTime.month < this.endTime.month) {
          isEnd = true;
        }
        if (this.startTime.month > this.endTime.month) {
          isEnd = false;
        }
        if (this.startTime.month == this.endTime.month) {
          if (this.startTime.day < this.endTime.day) {
            isEnd = true;
          }
          if (this.startTime.day > this.endTime.day) {
            isEnd = false;
          }
        }
      }
      if (isEnd) {
        return `${this.endTime.month}月${this.endTime.day}日${
          this.endTime.day_text
            ? this.endTime.day_text
            : "周" + this.weekData[this.endTime.week]
        }`;
      } else {
        return `${this.startTime.month}月${this.startTime.day}日${
          this.startTime.day_text
            ? this.startTime.day_text
            : "周" + this.weekData[this.startTime.week]
        }`;
      }
    },
  },
  methods: {
    // 初始化日历数据
    initTime() {
      let date = new Date();
      let now_year = date.getFullYear();
      let now_month = date.getMonth() + 1;
      let now_day = date.getDate();
      let monthBigger = ["1", "3", "5", "7", "8", "10", "12"];
      let monthNormal = ["4", "6", "9", "11"];
      let monthSmall = ["2"];
      let arr = [];
      for (let i = 0; i < 2; i++) {
        let obj = {
          monthTitle: "",
          list: [],
        };
        let time_title = "";
        if (i == 0) {
          time_title = `${now_year}年${
            now_month >= 10 ? now_month : "0" + now_month
          }月`;
          obj.monthTitle = time_title;
          let month_day_num = 0;
          if (monthBigger.includes(String(now_month))) {
            month_day_num = 31;
          }
          if (monthNormal.includes(String(now_month))) {
            month_day_num = 30;
          }
          if (monthSmall.includes(String(now_month))) {
            month_day_num = 28;
          }
          for (let k = 0; k < month_day_num; k++) {
            let dayObj = {
              year: now_year,
              month: now_month > 10 ? now_month : "0" + now_month,
              day: `${k + 1 >= 10 ? k + 1 : "0" + (k + 1)}`,
              num: 0,
              price: "",
              show: true,
            };
            dayObj["day_text"] = now_day == k + 1 ? "今天" : "";
            dayObj["week"] = new Date(
              `${dayObj.year}-${dayObj.month}-${dayObj.day}`
            ).getDay();
            obj.list.push(dayObj);
          }
        }
        if (i == 1) {
          let month_day_num = 0;
          let next_month = now_month + 1;
          if (next_month > 12) {
            next_month = 1;
          }
          time_title = `${now_month + 1 > 12 ? now_year + 1 : now_year}年${
            next_month > 10 ? next_month : "0" + next_month
          }月`;
          obj.monthTitle = time_title;
          if (monthBigger.includes(String(next_month))) {
            month_day_num = 31;
          }
          if (monthNormal.includes(String(next_month))) {
            month_day_num = 30;
          }
          if (monthSmall.includes(String(next_month))) {
            month_day_num = 28;
          }
          for (let k = 0; k < month_day_num; k++) {
            let dayObj = {
              year: now_month + 1 > 12 ? now_year + 1 : now_year,
              month: next_month > 10 ? next_month : "0" + next_month,
              day: `${k + 1 >= 10 ? k + 1 : "0" + (k + 1)}`,
              num: 0,
              price: "",
              show: true,
            };
            dayObj["week"] = new Date(
              `${dayObj.year}-${dayObj.month}-${dayObj.day}`
            ).getDay();
            obj.list.push(dayObj);
          }
        }
        arr.push(obj);
      }
      arr.forEach((d) => {
        if (d.list.length) {
          let first = d.list[0];
          let first_time = `${first.year}-${first.month}-${first.day}`;
          let week = new Date(first_time).getDay();
          let add_arr = [];
          if (week) {
            for (let a = 0; a < week; a++) {
              let obj = {
                year: first.year,
                month: "00",
                day: "00",
                num: 0,
                price: "",
                show: false,
              };
              add_arr.push(obj);
            }
            d.list = [...add_arr, ...d.list];
          }
        }
      });
      // 酒店预约
      if (this.product_type == 1) {
        let hotelArr = this.hotelData.date_book.date_book || [];
        arr.forEach((d) => {
          d.list.forEach((i) => {
            hotelArr.forEach((k) => {
              if (`${i.year}-${i.month}-${i.day}` == k.date) {
                i["num"] = k.num;
                i["price"] = k.price;
                i["canSelect"] = true;
              }
            });
          });
        });
      }
      return arr;
    },
    hidePopup() {
      this.showTimePopup = false;
    },
    showPopup() {
      this.showTimePopup = true;
      this.timeData = this.initTime();
      this.setListRange();
    },

    // 点击确认
    confirmTime() {
      let {num,startTime,endTime,checkList} = this;
      if (!startTime || !endTime)
        return this.$utils.toast("请完善日期选择!");

      if (num <= 0) return this.$utils.toast("请选择商品数量！!");

      let max = Math.min.apply(null,checkList.map(el=>el.num))
      if(num > max) return this.$utils.toast('已超过所选的最大库存~');

      // 判断库存
      this.checkRestNum();
    },

    // 判断库存
    checkRestNum() {
      // 筛选出选择的区间，并找出最小库存进行比对，看是否库存不足
      let arr = [];
      let selected_arr = [];
      // 在同一个月中
      if (this.startFatherIndex == this.endFatherIndex) {
        if (this.startI < this.endI) {
          arr = this.timeData[this.startFatherIndex].list.slice(
            this.startI,
            this.endI + 1
          );
          selected_arr = JSON.parse(JSON.stringify(arr));
        } else {
          arr = this.timeData[this.startFatherIndex].list.slice(
            this.endI,
            this.startI + 1
          );
          selected_arr = JSON.parse(JSON.stringify(arr));
        }
      }
      if (this.startFatherIndex < this.endFatherIndex) {
        let startData = this.timeData[this.startFatherIndex].list.slice(
          this.startI,
          this.timeData[this.startFatherIndex].list.length
        );
        let endData = this.timeData[this.endFatherIndex].list.slice(
          0,
          this.endI + 1
        );
        let end_data = endData.filter((d) => {
          return d.canSelect;
        });
        let total_data = [...startData, ...end_data];
        selected_arr = JSON.parse(JSON.stringify(total_data));
      }
      if (this.startFatherIndex > this.endFatherIndex) {
        let startData = this.timeData[this.endFatherIndex].list.slice(
          this.endI,
          this.timeData[this.endFatherIndex].list.length
        );
        let endData = this.timeData[this.startFatherIndex].list.slice(
          0,
          this.startI + 1
        );
        let end_data = endData.filter((d) => {
          return d.canSelect;
        });
        let total_data = [...startData, ...end_data];
        selected_arr = JSON.parse(JSON.stringify(total_data));
      }

      selected_arr.forEach((d) => {
        d["date"] = `${d.year}-${d.month}-${d.day}`;
      });

      // 可以提交
      this.$emit("timeConfirm", {
        num: this.num,
        start: this.startTime,
        end: this.endTime,
        list: selected_arr,
      });
    },

    //
    hasSelect(startListIndex, startI, endListIndex, endI) {
      let timeData = JSON.parse(JSON.stringify(this.timeData)),
        start,
        end,
        startP,
        endP,
        list;

      if (startListIndex == endListIndex) {
        if (startI < endI) {
          start = startI;
          end = endI;
        } else {
          start = endI;
          end = startI;
        }

        startP = startListIndex;
        endP = endListIndex;
      } else {
        if (startListIndex < endListIndex) {
          start = startI;
          end = endI;
          startP = startListIndex;
          endP = endListIndex;
        } else {
          start = endI;
          end = startI;
          startP = endListIndex;
          endP = startListIndex;
        }
      }

      if (startP === endP) {
        list = timeData[startP].list.splice(start, end - start);
      } else {
        let list1 = timeData[0].list,
          list2 = timeData[1].list;
        list = [
          ...list1.splice(start, list1.length - start),
          ...list2.splice(0, end).filter((el) => el.show),
        ];
      }

      if (list.every((el) => el.num)) {
        this.checkList = list;
        return true;
      }

      this.$utils.toast("此范围内库存不足请重新选择~");
      this.checkList = [];
      return false;
    },

    // 点击选择时间
    handleTimeItem(item, i, index) {
      if (!item?.canSelect) return;
      if (!item.num) {
        this.$utils.toast("此日期没有库存~");
        return;
      }
      if (!this.startI && !this.endI) {
        this.startFatherIndex = index;
        this.startI = i;
        this.startTime = item;
        this.setListRange();
        return;
      }
      if (!this.startI && this.endI) {
        this.startFatherIndex = index;
        this.startI = i;
        this.setListRange();
        this.startTime = item;
        return;
      }

      if (this.startI && !this.endI) {
        if (!this.hasSelect(this.startFatherIndex, this.startI, index, i))
          return;

        this.endFatherIndex = index;
        this.endI = i;
        this.endTime = item;
        this.setListRange();
        return;
      }

      if (this.startI && this.endI) {
        this.startFatherIndex = index;
        this.startI = i;
        this.endFatherIndex = null;
        this.endI = null;
        this.startTime = item;
        this.endTime = null;
        this.setListRange();
        return;
      }
    },
    // 设置选择区间
    setListRange() {
      if (!this.startI || !this.endI) {
        this.timeData.forEach((d) => {
          d["rangeStart"] = -1;
          d["rangeEnd"] = -1;
        });
        return;
      }

      // 如果在同一个月份里
      if (this.startFatherIndex == this.endFatherIndex) {
        this.timeData.forEach((d, index) => {
          if (index == this.startFatherIndex) {
            if (this.startI > this.endI) {
              d["rangeStart"] = this.endI;
              d["rangeEnd"] = this.startI;
            } else {
              d["rangeStart"] = this.startI;
              d["rangeEnd"] = this.endI;
            }
          }
        });
      } else {
        // 不在同一个月份里
        this.timeData.forEach((d, index) => {
          //  起点大(反选的)
          if (this.startFatherIndex > this.endFatherIndex) {
            if (index == 0) {
              d["rangeStart"] = this.endI;
              d["rangeEnd"] = d.list.length;
            } else {
              d["rangeStart"] = 0;
              d["rangeEnd"] = this.startI;
            }
          } else {
            if (index == 0) {
              d["rangeStart"] = this.startI;
              d["rangeEnd"] = d.list.length;
            } else {
              d["rangeStart"] = 0;
              d["rangeEnd"] = this.endI;
            }
          }
        });
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.popup-body {
  width: 100%;
  background-color: #ffffff;
  padding-top: 4.8vw;
  max-height: 85vh;
  position: relative;
  .popup-title {
    font-size: 32rpx;
    font-family: PingFang SC;
    font-weight: 600;
    color: #262626;
    margin-left: 4.8vw;
    padding-bottom: 4.267vw;
  }
  .time-list {
    width: 100%;
    padding-bottom: 13.34vw;

    .week-list {
      width: 100%;
      height: 108rpx;
      display: flex;
      align-items: center;
      justify-content: space-around;
      padding: 0 36rpx;
      .week-item {
        height: 100%;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        font-size: 28rpx;
        font-family: PingFang SC;
        font-weight: 400;
        color: #333333;
      }
      .weekend {
        color: #f0250e;
      }
    }

    .scroll-section {
      width: 100%;
      height: 800rpx;

      border-top: 1px solid #f2f2f2;
      border-bottom: 1px solid #f2f2f2;
      padding-bottom: calc(116rpx);
      .time-item {
        width: 100%;
        padding: 0 36rpx;

        .time-title {
          width: 100%;
          height: 96rpx;
          display: flex;
          align-items: center;
          font-size: 26rpx;
          font-family: PingFang SC;
          font-weight: 600;
          color: #333333;
        }
        .time-calendar {
          width: 100%;
          display: flex;
          flex-wrap: wrap;
          background: #ffffff;
          .calendar-item {
            width: 14.285%;
            height: 110rpx;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            margin-bottom: 8rpx;
            .day-text {
              height: 28rpx;
              font-size: 20rpx;
              font-family: PingFang SC;
              font-weight: 400;
              color: #262626;
            }
            .day-time {
              font-size: 26rpx;
              font-family: PingFang SC;
              font-weight: 600;
              color: #262626;
            }

            .day-down {
              height: 28rpx;
              font-size: 20rpx;
              font-family: PingFang SC;
              font-weight: 600;
              color: #f0250e;
            }

            &.disabled {
              background: #f5f5f5;
              border-radius: 12rpx;

              .day-down {
                color: #000;
              }
            }
          }
          .calendar-hide {
            opacity: 0;
          }
          .range-item {
            background: #f0250e;
            border-radius: 12rpx;
            .day-text {
              color: #ffffff;
            }
            .day-time {
              color: #ffffff;
            }
            .day-down {
              color: #ffffff;
            }
          }
          .in-range {
            background: #fcedeb;
          }
          .start-range-item {
            border-top-right-radius: 0;
            border-bottom-right-radius: 0;
          }
          .end-range-item {
            border-top-left-radius: 0;
            border-bottom-left-radius: 0;
          }
          .has-radius {
            border-radius: 12rpx;
          }
        }
      }
    }
  }
  .close-icon {
    width: 14.93vw;
    height: 14.93vw;
    position: absolute;
    right: 0;
    top: 0;
    z-index: 11;
    display: flex;
    justify-content: center;
    align-items: center;
    .icon-box {
      width: 5.34vw;
      height: 5.34vw;
      border-radius: 50%;
      display: flex;
      justify-content: center;
      align-items: center;
      background-color: #f2f1f2;
      .iconfont {
        // color: #8c8c8c;
        font-weight: 600;
        font-size: 36rpx;
      }
    }
  }

  .foot-btns {
    width: 100%;
    position: absolute;
    left: 0;
    bottom: 0;
    z-index: 121;
    border-top: 1px solid #f0f1f3;
    .selected-section {
      width: 100%;
      height: 116rpx;
      background: #ffffff;
      padding-top: 14rpx;
      .select-title {
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        .start,
        .end {
          flex: 1;
          font-size: 22rpx;
          font-family: PingFang SC;
          font-weight: 400;
          color: #8c8c8c;
          text-align: center;
        }
        .middle {
          width: 152rpx;
        }
      }
      .select-date {
        width: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
        .split-line {
          width: 152rpx;
          font-size: 32rpx;
          font-family: PingFang SC;
          font-weight: 600;
          color: #000000;
          text-align: center;
        }
        .selected-start {
          flex: 1;
          height: 100%;
          font-size: 32rpx;
          font-family: PingFang SC;
          font-weight: 600;
          color: #000000;
          text-align: center;
        }
        .selected-end {
          flex: 1;
          height: 100%;
          font-size: 32rpx;
          font-family: PingFang SC;
          font-weight: 600;
          color: #000000;
          text-align: center;
        }
      }
    }

    .select-num {
      width: 100%;
      height: 116rpx;
      background: #ffffff;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 36rpx;
      .shop-num-text {
        font-size: 26rpx;
        font-family: PingFang SC;
        font-weight: 600;
        color: #262626;
      }
    }
    .foot-content {
      width: 100%;
      height: 13.34vw;
      padding: 0 4.8vw;
      display: flex;
      justify-content: center;
      align-items: center;
      .foot-btn {
        width: 100%;
        height: 10.134vw;
        background: linear-gradient(90deg, #f22407 0%, #f84d17 100%);
        border-radius: 5.067vw;
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 26rpx;
        font-family: PingFang SC;
        font-weight: 600;
        color: #ffffff;
      }
      .btn-grey {
        background: #e4e4e4;
      }
    }

    .safe {
      padding-bottom: env(safe-area-inset-bottom);
    }
  }
}
</style>
